package org.example.spring.factory;

import org.example.spring.annotation.MyComponent;
import org.example.spring.annotation.MyRepository;
import org.example.spring.annotation.MyService;
import org.example.spring.config.MyGenericBeanDefinition;
import org.example.spring.util.NameGenerator;

import java.io.File;
import java.util.Objects;

public class MyGeneralBeanDefinitionReader {

    protected MyBeanFactory myBeanFactory;

    public MyGeneralBeanDefinitionReader(MyBeanFactory myBeanFactory) {
        this.myBeanFactory = myBeanFactory;
    }

    protected void doScannerPackage(String basePackage) throws ClassNotFoundException {

        String filePath = Objects.requireNonNull(Thread.currentThread().getContextClassLoader()
                .getResource(basePackage.replaceAll("\\.", "/"))).getFile();
        File dir = new File(filePath);

        for (File file : Objects.requireNonNull(dir.listFiles())) {
            if (file.isDirectory()) {
                doScannerPackage(basePackage + "." + file.getName());
            } else {
                if (!file.getName().contains(".class")) {
                    continue;
                }
                String className = basePackage + "." + file.getName().replace(".class", "");

                Class<?> clazz = Class.forName(className);

                if (clazz.isAnnotationPresent(MyService.class)
                    || clazz.isAnnotationPresent(MyRepository.class)
                    || clazz.isAnnotationPresent(MyComponent.class)) {

                    MyGenericBeanDefinition myGenericBeanDefinition = new MyGenericBeanDefinition();
                    myGenericBeanDefinition.setBeanClass(clazz);

                    String beanName;
                    for (Class inf : clazz.getInterfaces()) {
                        beanName = NameGenerator.nameGenerator(inf.getSimpleName());
                        myGenericBeanDefinition.setBeanName(beanName);
                        this.myBeanFactory.registerBeanDefinition(beanName, myGenericBeanDefinition);
                    }
                    beanName = NameGenerator.nameGenerator(clazz.getSimpleName());
                    myGenericBeanDefinition.setBeanName(beanName);
                    this.myBeanFactory.registerBeanDefinition(beanName, myGenericBeanDefinition);
                }
            }
        }
    }

}
